/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package database.entitymanager;

import database.entity.User;
import database.entitymanager.exceptions.NonexistentEntityException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import database.entity.UserGroup;
import database.entity.ShoppingCart;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Stefan
 */
public class UserManager {

 
    private static EntityManagerFactory emf = EntityFactoryHolder.getInstance();

    public static EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public static void create(User user) {
        if (user.getShoppingCartList() == null) {
            user.setShoppingCartList(new ArrayList<ShoppingCart>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            UserGroup userGroup = user.getUserGroup();
            if (userGroup != null) {
                userGroup = em.getReference(userGroup.getClass(), userGroup.getUgid());
                user.setUserGroup(userGroup);
            }
            List<ShoppingCart> attachedShoppingCartList = new ArrayList<ShoppingCart>();
            for (ShoppingCart shoppingCartListShoppingCartToAttach : user.getShoppingCartList()) {
                shoppingCartListShoppingCartToAttach = em.getReference(shoppingCartListShoppingCartToAttach.getClass(), shoppingCartListShoppingCartToAttach.getCartid());
                attachedShoppingCartList.add(shoppingCartListShoppingCartToAttach);
            }
            user.setShoppingCartList(attachedShoppingCartList);
            em.persist(user);
            if (userGroup != null) {
                userGroup.getUserList().add(user);
                userGroup = em.merge(userGroup);
            }
            for (ShoppingCart shoppingCartListShoppingCart : user.getShoppingCartList()) {
                User oldUserOfShoppingCartListShoppingCart = shoppingCartListShoppingCart.getUser();
                shoppingCartListShoppingCart.setUser(user);
                shoppingCartListShoppingCart = em.merge(shoppingCartListShoppingCart);
                if (oldUserOfShoppingCartListShoppingCart != null) {
                    oldUserOfShoppingCartListShoppingCart.getShoppingCartList().remove(shoppingCartListShoppingCart);
                    oldUserOfShoppingCartListShoppingCart = em.merge(oldUserOfShoppingCartListShoppingCart);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public static void edit(User user) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User persistentUser = em.find(User.class, user.getUserid());
            UserGroup userGroupOld = persistentUser.getUserGroup();
            UserGroup userGroupNew = user.getUserGroup();
            List<ShoppingCart> shoppingCartListOld = persistentUser.getShoppingCartList();
            List<ShoppingCart> shoppingCartListNew = user.getShoppingCartList();
            if (userGroupNew != null) {
                userGroupNew = em.getReference(userGroupNew.getClass(), userGroupNew.getUgid());
                user.setUserGroup(userGroupNew);
            }
            List<ShoppingCart> attachedShoppingCartListNew = new ArrayList<ShoppingCart>();
            for (ShoppingCart shoppingCartListNewShoppingCartToAttach : shoppingCartListNew) {
                shoppingCartListNewShoppingCartToAttach = em.getReference(shoppingCartListNewShoppingCartToAttach.getClass(), shoppingCartListNewShoppingCartToAttach.getCartid());
                attachedShoppingCartListNew.add(shoppingCartListNewShoppingCartToAttach);
            }
            shoppingCartListNew = attachedShoppingCartListNew;
            user.setShoppingCartList(shoppingCartListNew);
            user = em.merge(user);
            if (userGroupOld != null && !userGroupOld.equals(userGroupNew)) {
                userGroupOld.getUserList().remove(user);
                userGroupOld = em.merge(userGroupOld);
            }
            if (userGroupNew != null && !userGroupNew.equals(userGroupOld)) {
                userGroupNew.getUserList().add(user);
                userGroupNew = em.merge(userGroupNew);
            }
            for (ShoppingCart shoppingCartListOldShoppingCart : shoppingCartListOld) {
                if (!shoppingCartListNew.contains(shoppingCartListOldShoppingCart)) {
                    shoppingCartListOldShoppingCart.setUser(null);
                    shoppingCartListOldShoppingCart = em.merge(shoppingCartListOldShoppingCart);
                }
            }
            for (ShoppingCart shoppingCartListNewShoppingCart : shoppingCartListNew) {
                if (!shoppingCartListOld.contains(shoppingCartListNewShoppingCart)) {
                    User oldUserOfShoppingCartListNewShoppingCart = shoppingCartListNewShoppingCart.getUser();
                    shoppingCartListNewShoppingCart.setUser(user);
                    shoppingCartListNewShoppingCart = em.merge(shoppingCartListNewShoppingCart);
                    if (oldUserOfShoppingCartListNewShoppingCart != null && !oldUserOfShoppingCartListNewShoppingCart.equals(user)) {
                        oldUserOfShoppingCartListNewShoppingCart.getShoppingCartList().remove(shoppingCartListNewShoppingCart);
                        oldUserOfShoppingCartListNewShoppingCart = em.merge(oldUserOfShoppingCartListNewShoppingCart);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = user.getUserid();
                if (findUser(id) == null) {
                    throw new NonexistentEntityException("The user with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public static void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User user;
            try {
                user = em.getReference(User.class, id);
                user.getUserid();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            UserGroup userGroup = user.getUserGroup();
            if (userGroup != null) {
                userGroup.getUserList().remove(user);
                userGroup = em.merge(userGroup);
            }
            List<ShoppingCart> shoppingCartList = user.getShoppingCartList();
            for (ShoppingCart shoppingCartListShoppingCart : shoppingCartList) {
                shoppingCartListShoppingCart.setUser(null);
                shoppingCartListShoppingCart = em.merge(shoppingCartListShoppingCart);
            }
            em.remove(user);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public static List<User> findUserEntities() {
        return findUserEntities(true, -1, -1);
    }

    public static List<User> findUserEntities(int maxResults, int firstResult) {
        return findUserEntities(false, maxResults, firstResult);
    }

    private static List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(User.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public static User findUser(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    public static int getUserCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<User> rt = cq.from(User.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
